<?php

## filter customfields
add_filter( 'parse_query', 'ba_admin_posts_filter' );
add_action( 'restrict_manage_posts', 'ba_admin_posts_filter_restrict_manage_posts' );
function ba_admin_posts_filter( $query )
{
    global $pagenow;
   
    if ( is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_NAME']) && $_GET['ADMIN_FILTER_FIELD_NAME'] != '') {
        $query->query_vars['meta_key'] = $_GET['ADMIN_FILTER_FIELD_NAME'];       
        //$query->query_vars['meta_key'] = "feature";
    if (isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '')
        $query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE'];
    }
}
function ba_admin_posts_filter_restrict_manage_posts()
{
    global $wpdb ,$typenow;
    $sql = 'SELECT DISTINCT meta_key FROM '.$wpdb->postmeta.' ORDER BY 1';
    $fields = $wpdb->get_results($sql, ARRAY_N);
    if($typenow == 'post' || $typenow == 'adv')
    {    
	?>	
	<select name="ADMIN_FILTER_FIELD_NAME">
	<option value=""><?php _e('Filter By Custom Fields', 'display'); ?></option>
	<?php
	    $current = isset($_GET['ADMIN_FILTER_FIELD_NAME'])? $_GET['ADMIN_FILTER_FIELD_NAME']:'';
	    $current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';
	    foreach ($fields as $field) 
	    {
	    	$result = db_get_name_for_filter($field[0]);
	        if($result)
	        {
	        	$tamp = $field[0];
	        	if($current == $tamp)
	        		echo '<option value="'.$field[0].'" selected="selected">'.$result.'</option>';
	        	else 
	        		echo '<option value="'.$field[0].'">'.$result.'</option>';
	        }    	
	    }
	?>
	</select> <input type="hidden" name="ADMIN_FILTER_FIELD_VALUE" value="display" />
	<?php
    }
}
